﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.Net;
using System.IO;

namespace QiHe
{
    public partial class Add_EGN : Form
    {
        class CheckSumBuilder
        {
            // 计算并获取CheckSum
            public static String getCheckSum(String appSecret, String nonce, String curTime)
            {
                byte[] data = Encoding.Default.GetBytes(appSecret + nonce + curTime);
                byte[] result;

                SHA1 sha = new SHA1CryptoServiceProvider();
                // This is one implementation of the abstract class SHA1.
                result = sha.ComputeHash(data);

                return getFormattedText(result);
            }

            // 计算并获取md5值
            public static String getMD5(String requestBody)
            {
                if (requestBody == null)
                    return null;

                // Create a new instance of the MD5CryptoServiceProvider object.
                MD5 md5Hasher = MD5.Create();

                // Convert the input string to a byte array and compute the hash.
                byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(requestBody));

                // Create a new Stringbuilder to collect the bytes
                // and create a string.
                StringBuilder sBuilder = new StringBuilder();

                // Loop through each byte of the hashed data 
                // and format each one as a hexadecimal string.
                for (int i = 0; i < data.Length; i++)
                {
                    sBuilder.Append(data[i].ToString("x2"));
                }

                // Return the hexadecimal string.
                return getFormattedText(Encoding.Default.GetBytes(sBuilder.ToString()));
            }

            private static String getFormattedText(byte[] bytes)
            {
                char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
                int len = bytes.Length;
                StringBuilder buf = new StringBuilder(len * 2);
                for (int j = 0; j < len; j++)
                {
                    buf.Append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
                    buf.Append(HEX_DIGITS[bytes[j] & 0x0f]);
                }
                return buf.ToString();
            }
        }

        class HttpClient
        {
            public static string HttpPost(string url, Stream data, IDictionary<object, string> headers = null)
            {
                System.Net.WebRequest request = HttpWebRequest.Create(url);
                request.Method = "POST";
                if (data != null)
                    request.ContentLength = data.Length;
                request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";

                if (headers != null)
                {
                    foreach (var v in headers)
                    {
                        if (v.Key is HttpRequestHeader)
                            request.Headers[(HttpRequestHeader)v.Key] = v.Value;
                        else
                            request.Headers[v.Key.ToString()] = v.Value;
                    }
                }
                HttpWebResponse response = null;
                try
                {
                    // Get the response.
                    response = (HttpWebResponse)request.GetResponse();
                    // Display the status.
                    Console.WriteLine(response.StatusDescription);
                    // Get the stream containing content returned by the server.
                    Stream dataStream = response.GetResponseStream();
                    // Open the stream using a StreamReader for easy access.
                    StreamReader reader = new StreamReader(dataStream);
                    // Read the content.
                    string responseFromServer = reader.ReadToEnd();
                    // Display the content.
                    return responseFromServer;


                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(response.StatusDescription);
                    return "1";
                }


                
            }
        }
        DataSet DeptList;
        public Add_EGN()
        {
            InitializeComponent();
             
        }

        private void Add_EGN_Load(object sender, EventArgs e)
        {

            MedEQ.Service1 sop = new MedEQ.Service1();
            DeptList = sop.HSP_Department_List(DataTemp.HSPID);

            comboBox1.DataSource = DeptList.Tables[0];
            comboBox1.DisplayMember = "Name";
            comboBox1.ValueMember = "ID";
        }

        private void button1_Click(object sender, EventArgs e)
        {
         


            MedEQ.Service1 sop = new MedEQ.Service1();
            string result = sop.Add_User(textBox1.Text, textBox3.Text, textBox2.Text, textBox1.Text, comboBox1.SelectedValue.ToString(), textBox5.Text.Trim());

            if (result.Equals("3"))
                MessageBox.Show("用户名已存在！");
            if (result.Equals("4"))
                MessageBox.Show("中文名已存在！");
            if (result.Length > 2)
            {


              //  MessageBox.Show(result.ToString());
                String url = "https://api.netease.im/nimserver/user/create.action";
                url += "?accid=" + textBox1.Text;//TO开发者：accid填要创建的id

                String appKey = "5d1fd1568f14f138a75ce1ead82f47b3";//TO开发者：假数据，具体参考开发文档
                String appSecret = "122d5e94051d";//TO开发者：假数据，具体参考开发文档
                String nonce = "12345";//TO开发者：具体参考开发文档

                TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
                Int32 ticks = System.Convert.ToInt32(ts.TotalSeconds);
                String curTime = ticks.ToString();
                String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);

                IDictionary<object, String> headers = new Dictionary<object, String>();
                headers["AppKey"] = appKey;
                headers["Nonce"] = nonce;
                headers["CurTime"] = curTime;
                headers["CheckSum"] = checkSum;
                headers["ContentType"] = "application/x-www-form-urlencoded;charset=utf-8";
                string rs = HttpClient.HttpPost(url, null, headers);
                 
                int i = rs.IndexOf("\"token\":\"")+9;
            int j = rs.IndexOf("\",\"accid");
            string str = rs.Substring(i, j - i);
            textBox4.Text = str;
            sop.Update_User_Token(textBox1.Text.Trim(), str);
            this.Dispose();

            }
        }

        private void skinComboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (skinComboBox1.Text == "管理员")
            {
                textBox5.Text = "11";
            }
            if (skinComboBox1.Text == "工程师")
            {
                textBox5.Text = "4";
            }
            if (skinComboBox1.Text == "设备管理员")
            {
                textBox5.Text = "6";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            String url = "https://api.netease.im/sms/sendcode.action";
                url += "?mobile=13604046321";//TO开发者：accid填要创建的id

                String appKey = "5d1fd1568f14f138a75ce1ead82f47b3";//TO开发者：假数据，具体参考开发文档
                String appSecret = "122d5e94051d";//TO开发者：假数据，具体参考开发文档
                String nonce = "12345";//TO开发者：具体参考开发文档

                TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
                Int32 ticks = System.Convert.ToInt32(ts.TotalSeconds);
                String curTime = ticks.ToString();
                String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);

                IDictionary<object, String> headers = new Dictionary<object, String>();
                headers["AppKey"] = appKey;
                headers["Nonce"] = nonce;
                headers["CurTime"] = curTime;
                headers["CheckSum"] = checkSum;
                headers["ContentType"] = "application/x-www-form-urlencoded;charset=utf-8";
                string rs = HttpClient.HttpPost(url, null, headers);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            String url = "https://api.netease.im/sms/sendtemplate.action";
            url += "?templateid=7408&mobiles=['13604046321']&params=['hello','555']";//TO开发者：accid填要创建的id

            String appKey = "5d1fd1568f14f138a75ce1ead82f47b3";//TO开发者：假数据，具体参考开发文档
            String appSecret = "122d5e94051d";//TO开发者：假数据，具体参考开发文档
            String nonce = "12345";//TO开发者：具体参考开发文档

            TimeSpan ts = DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1);
            Int32 ticks = System.Convert.ToInt32(ts.TotalSeconds);
            String curTime = ticks.ToString();
            String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);

            IDictionary<object, String> headers = new Dictionary<object, String>();
            headers["AppKey"] = appKey;
            headers["Nonce"] = nonce;
            headers["CurTime"] = curTime;
            headers["CheckSum"] = checkSum;
            headers["ContentType"] = "application/x-www-form-urlencoded;charset=utf-8";
            string rs = HttpClient.HttpPost(url, null, headers);
        }
    }
}
